<?php
class doom_router {

    static public function dispatch($ctrlName, $actionName = null) {
        //如果未指定$actionName，则从请求中取，或指定默认值
        if ($actionName === null) {
            $actionName = (isset($_REQUEST[doom_config::$CTRL_ACTION_NAME]) && trim($_REQUEST[doom_config::$CTRL_ACTION_NAME]) != '') ? $_REQUEST[doom_config::$CTRL_ACTION_NAME] : 'default';
        }
        //检查action name是否为合法字符串
        if (!preg_match('/^[0-9a-z_\-]+$/i', $actionName)) {
            //TODO 
            echo 'Error: Action Name Not Allowed!';
            exit();
        }
        
        $ctrlClassName = 'ctrl_' . str_replace('.', '_', $ctrlName);
        if (!class_exists($ctrlClassName)) {
            //TODO
            echo 'Error: ' . $ctrlClassName . ' Not Exist.';
            exit();
        }
        
        $methodName = 'action_' . $actionName;
        
        $request = new doom_ctrl_request();
        $response = new doom_ctrl_response();
        $template = new doom_ctrl_template($request, $response);
        
        $ctrl = new $ctrlClassName($request, $response, $template);
        
        if (!method_exists($ctrl, $methodName)) {
            //TODO
            echo 'Error: Method Not Found "' . $methodName . '"';
            exit();
        }
        $ctrl->$methodName($request, $response, $template);
    }
}